package com.pantuo.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pantuo.common.exception.ServiceException;
import com.pantuo.common.utils.DataTablePage;
import com.pantuo.common.utils.TableRequest;
import com.pantuo.sys.dao.EquipmentDao;
import com.pantuo.sys.pojo.Equipment;
import com.pantuo.sys.service.EquipmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class EquipmentServiceImpl implements EquipmentService {

    @Autowired
    private EquipmentDao equipmentDao;

    @Override
    public PageImpl<Map<String, Object>> findPageObjects(TableRequest request) {
        //获取起始索引
        int start = request.getStart();
        //获取页面大小
        int length = request.getLength();
        //获取查询条件，用map封装
        Map<String, String> filter = request.getFilter();
        //获取排序字段和排序规则 asc or desc
        List<Map<String, String>> orderList = request.getOrder();
        //一页数据的集合
        List<Map<String, Object>> commonRecords = null;
        //数据的总数
        Long total = null;
        //如果排序条件为空则默认按照创建时间排序(最后创建的用户排在最前面)
        if (orderList == null) {
            total = equipmentDao.getTotal(filter);
            if (total == 0) {
                throw new ServiceException("暂无记录");
            }
            commonRecords = equipmentDao.findAllObjects(filter, null, start, length);
            return new DataTablePage(new PageImpl<Map<String, Object>>(commonRecords, PageRequest.of(start, length), total));
        }
        //如果排序不为空
        Map<String, String> orderMap = orderList.get(0);
        total = equipmentDao.getTotal(filter);
        if (total == 0) {
            throw new ServiceException("暂无记录");
        }
        commonRecords = equipmentDao.findAllObjects(filter, orderMap, start, length);
        return new DataTablePage(new PageImpl<Map<String, Object>>(commonRecords, PageRequest.of(start, length), total));
    }

    @Override
    public Integer findTotalByVId(Integer id) {
        QueryWrapper<Equipment> queryWrapper = new QueryWrapper();
        queryWrapper.eq("vehicleId_i", id);
        return equipmentDao.selectCount(queryWrapper);
    }
}
